<template>
  <div class="auth-container">
    <div class="auth-card">
      <div class="auth-header">
        <h2>注册</h2>
        <p>加入云顶AI自习室，开启智能学习之旅</p>
      </div>

      <!-- <el-steps :active="currentStep" align-center class="register-steps">
        <el-step title="账号信息" />
        <el-step title="基础信息" />
        <el-step title="学习信息" />
        <el-step title="偏好设置" />
      </el-steps> -->
      <el-form
       ref="accountFormRef"
        :model="accountForm"
        :rules="registerRules"
        label-width="70px"
        class="login-form"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="accountForm.username"
            placeholder="3-20 个字符"
            clearable
          />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="accountForm.password"
            type="password"
            placeholder="6 位及以上"
            show-password
            clearable
          />
        </el-form-item>
        <el-form-item label="确认" prop="confirmPassword">
          <el-input
            v-model="accountForm.confirmPassword"
            type="password"
            placeholder="再次输入密码"
            show-password
            clearable
          />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input
            v-model="accountForm.email"
            placeholder="请输入邮箱"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" style="width: 100%" @click="handleRegister"
            >注册</el-button
          >
        </el-form-item>
      </el-form>

      <div class="auth-footer">
        <span class="footer-text">已有账号？</span>
        <el-link type="primary" @click="goToLogin"  class="footer-link">立即登录</el-link>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from "vue";
import { useRouter } from "vue-router";
import { useUserStore } from "@/stores";
import { ElMessage } from "element-plus";
import { User, Lock, Phone, Message } from "@element-plus/icons-vue";
import type { FormInstance, FormRules } from "element-plus";
import { register } from "@/api/user";

const router = useRouter();
const userStore = useUserStore();

const currentStep = ref(0);
const loading = ref(false);
const smsCountdown = ref(0);

const accountFormRef = ref<FormInstance>();
const basicFormRef = ref<FormInstance>();
const studyFormRef = ref<FormInstance>();
const preferencesFormRef = ref<FormInstance>();

const accountForm = reactive({
  username: "",
  password: "",
  confirmPassword: "",
  phone: "",
  smsCode: "",
  email: "",
});

const basicForm = reactive({
  nickname: "",
  email: "",
  gender: "",
  education: "",
});

const studyForm = reactive({
  studySubjects: [],
  studyGoal: "",
  dailyStudyTime: "",
});

const preferencesForm = reactive({
  defaultCameraOff: true,
  defaultMicOff: true,
  hidePersonalInfo: false,
  enableAIReminder: true,
  autoGeneratePlan: true,
});

const validateConfirmPassword = (rule: any, value: any, callback: any) => {
  if (value !== accountForm.password) {
    callback(new Error("两次输入的密码不一致"));
  } else {
    callback();
  }
};

// 在 validateConfirmPassword 函数下方添加邮箱验证函数
const validateEmail = (rule: any, value: any, callback: any) => {
  // 通用邮箱正则表达式
  const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
  
  if (!value) {
    callback(new Error("请输入邮箱"));
  } else if (!emailRegex.test(value)) {
    callback(new Error("请输入正确的邮箱格式"));
  } else {
    callback();
  }
};

// 修改 registerRules 对象，添加邮箱验证规则
const registerRules: FormRules = {
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 3, max: 20, message: "用户名长度在3到20个字符", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, message: "密码长度不能少于6位", trigger: "blur" },
  ],
  confirmPassword: [
    { required: true, message: "请确认密码", trigger: "blur" },
    { validator: validateConfirmPassword, trigger: "blur" },
  ],
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    { validator: validateEmail, trigger: "blur" },
  ],
};



const accountRules: FormRules = {
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 3, max: 20, message: "用户名长度在3到20个字符", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, message: "密码长度不能少于6位", trigger: "blur" },
  ],
  confirmPassword: [
    { required: true, message: "请确认密码", trigger: "blur" },
    { validator: validateConfirmPassword, trigger: "blur" },
  ],
};

const nextStep = async () => {
  const forms = [
    accountFormRef,
    basicFormRef,
    studyFormRef,
    preferencesFormRef,
  ];
  const currentForm = forms[currentStep.value];

  if (currentForm.value) {
    try {
      await currentForm.value.validate();
      currentStep.value++;
    } catch (error) {
      ElMessage.error("请填写完整信息");
    }
  }
};

const previousStep = () => {
  if (currentStep.value > 0) {
    currentStep.value--;
  }
};

const sendSmsCode = () => {
  if (!accountForm.phone) {
    ElMessage.warning("请先输入手机号");
    return;
  }

  smsCountdown.value = 60;
  const timer = setInterval(() => {
    smsCountdown.value--;
    if (smsCountdown.value <= 0) {
      clearInterval(timer);
    }
  }, 1000);

  ElMessage.success("验证码已发送");
};
const handleRegister = async () => {
   // 先进行表单验证
  try {
    await accountFormRef.value?.validate();
  } catch (error) {
    ElMessage.error("请检查表单信息是否正确");
    return;
  }

  loading.value = true;
  try {
    // 调用后端注册接口
    const res = await register({
      username: accountForm.username,
      password: accountForm.password,
      email: accountForm.email,
    });
    console.log("注册结果：", res);

    if (res.code === 200) {
      ElMessage.success("注册成功，请登录！");
      router.push("/auth/login");
    } else {
      ElMessage.error(res?.msg || "注册失败，请重试");
    }
  } catch (error) {
    ElMessage.error("请填写完整信息");
  } finally {
    loading.value = false;
  }
};

// const handleRegister = async () => {
//   try {
//     loading.value = true;

//     const mockUser = {
//       id: Math.random().toString(36).substr(2, 9),
//       username: accountForm.username,
//       nickname: basicForm.nickname,
//       email: basicForm.email,
//       phone: accountForm.phone,
//       avatar: "",
//       gender: basicForm.gender,
//       education: basicForm.education,
//       studySubjects: studyForm.studySubjects,
//       studyTime: 0,
//       isOnline: true,
//     };

//     userStore.login(mockUser);
//     ElMessage.success("注册成功，欢迎加入云顶AI自习室！");
//     router.push("/");
//   } catch (error) {
//     ElMessage.error("注册失败，请重试");
//   } finally {
//     loading.value = false;
//   }
// };
const registrHandler = async () => {
  const result = await register({
    username: accountForm.username,
    password: accountForm.password,
  });
};

const goToLogin = () => {
  router.push("/auth/login");
};
</script>

<style scoped>
.auth-container {
  width: 100%;
  max-width: 500px;
}

.auth-card {
  background: white;
  border-radius: 16px;
  padding: 40px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
}

.auth-header {
  text-align: center;
  margin-bottom: 30px;
}

.auth-header h2 {
  margin: 0 0 8px 0;
  color: #2c3e50;
  font-size: 2rem;
  font-weight: bold;
}

.auth-header p {
  margin: 0;
  color: #7f8c8d;
}

.register-steps {
  margin-bottom: 40px;
}

.step-content {
  min-height: 300px;
  margin-bottom: 30px;
}

.step-form {
  padding: 20px 0;
}

.phone-input {
  display: flex;
  gap: 12px;
}

.phone-input .el-input {
  flex: 1;
}

.preferences-section {
  margin-bottom: 24px;
}

.preferences-section h4 {
  margin-bottom: 16px;
  color: #2c3e50;
  font-weight: 600;
}

.step-actions {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.auth-footer {
  display: flex;
  align-items: center;
  justify-content: flex-end; /* 靠右对齐 */
  gap: 8px; /* 两个元素之间的间距 */
  margin-top: 20px;
}
.footer-text,
.footer-link {
  font-size: 14px;
  line-height: 20px; /* 统一字体高度 */
}

.footer-text {
  color: #7f8c8d;
}

.footer-link {
  height: 20px; /* 确保链接高度一致 */
}

.footer-link :deep(.el-link__inner) {
  font-size: 14px;
  line-height: 20px;
  height: 20px;
}

:deep(.el-checkbox-group) {
  display: flex;
  flex-direction: column;
  gap: 12px;
}
</style>
